import { message } from 'ant-design-vue';
import { AxiosRequestConfig, AxiosResponse } from 'axios';
import { g6CeateAxiosHttp, g6HttpErrorStatus } from 'glasssix-utils-ts';

const toLoginPage = (): void => {
	let timer = '';
	setTimeout(() => {
		window.location.href = `http://${window.location.host}/login`;
		timer = '';
		clearTimeout(timer);
	}, 600);
};

// 请求拦截器
const reqCallback = <T extends AxiosRequestConfig>(config: T): any => {
	if (config.headers) {
		config.headers.token = sessionStorage.getItem('token') ?? '';
	}
	return config;
};

// 响应拦截器, 正确响应的处理
const resCallback = (response: AxiosResponse): any => {
	if (response?.status === 200) {
		// 图片下载时,返回文件名和文件
		if (response.config.headers.customFlag === 'downloadAlarmImgs') {
			return { title: response.headers['content-disposition'], data: response.data };
		}

		// 二进制数据
		if (response.config.responseType === 'blob' || response.config.responseType === 'arraybuffer') {
			console.log('二进制数据===', response);

			if (!Reflect.has(response, 'data') || !response?.data) {
				return { code: -1 };
			}
			return {
				code: 0,
				data: response?.data,
				title: response.headers['content-disposition'] ? decodeURI(response.headers['content-disposition']) : ''
			};
			// return response?.data;
		}
		if (Reflect.has(response, 'data')) {
			if (response?.data.code !== 0 && !response.config.headers['hide-message']) {
				// 当上传走minIO时获取不到data，状态为200则必定成功
				if (!(response.config.headers.customFlag === 'vesionUpload')) {
					g6HttpErrorStatus(response?.data.code, (msg) => message.error(msg), response?.data.message);
					return response?.data;
				}
			}

			return response?.data;
		}
	}
};

// 响应拦截器, 错误响应的处理
const resErrorCallback = (error: any): any => {
	if (error && error.response) {
		g6HttpErrorStatus(error.response.status, (msg) => {
			message.error(msg);
			error.response.status === 401 && toLoginPage();
		});

		return Promise.reject(error.response);
	}
	return Promise.reject(error);
};

const blobToString = (blob: Blob) => {
	// eslint-disable-next-line promise/avoid-new
	return new Promise((resolve, reject) => {
		const reader = new FileReader();

		// 设置读取完成后的处理
		reader.onload = function (event) {
			try {
				if (event.target) {
					resolve(event.target.result);
				}
			} catch (error) {
				reject(new Error('Failed to parse JSON: ' + error));
			}
		};

		// 设置读取错误的处理
		reader.onerror = function () {
			reject(new Error('Failed to read Blob'));
		};

		// 读取 Blob 的内容为文本
		reader.readAsText(blob);
	});
};

// const blobToJson2 = async (data: Blob) => {
// 	const callBackFn = () => {
// 		const reader = new FileReader(); //创建一个FileReader实例
// 		reader.readAsText(data); //读取文件,结果用字符串形式表示
// 		// eslint-disable-next-line promise/avoid-new
// 		return new Promise((resolve, reject) => {
// 			const reader = new FileReader();
// 			reader.onload = () => resolve(reader.result);
// 			reader.onerror = () => reject(reader.error);
// 			reader.readAsText(data, 'utf-8');
// 		});
// 	};
// 	const res = await callBackFn();
// 	return res ? JSON.parse(res as string) : {};
// };

class CustomAxiosHttp extends g6CeateAxiosHttp {
	downloadAlarmImgs(url: string) {
		// eslint-disable-next-line @typescript-eslint/explicit-function-return-type
		return async (params?: Record<any, any>, config?: Omit<AxiosRequestConfig, 'url' | 'params' | 'method'>) => {
			const res: Record<string, any> = await this.httpClient.get(url, {
				params,
				...{ headers: { customFlag: 'downloadAlarmImgs' }, ...config }
			});
			console.log('downloadAlarmImgs', res);

			if (!res || res.data.size === 0) {
				return { code: -100, message: '下载错误' };
			}

			if (res.data.type === 'application/json') {
				const jsonRes: any = await blobToString(new Blob([res.data]));
				console.log('downloadAlarmImgs', { code: -100, message: jsonRes });

				return { code: -100, message: jsonRes };
			}

			return { code: 0, message: '下载成功', data: res };
		};
	}

	getTablePostApi(url: string, otherDataKeys?: string[]) {
		return async (params: any, config?: any) => {
			const returnData: any = { status: '', list: [], total: 0, otherDatas: {} };
			const res: Record<string, any> = await this.postHttp(url)(params, config);
			if (res.code === 0) {
				returnData.status = 'success';
				returnData.list = res.data.records;
				returnData.total = res.data.total;
				if (Array.isArray(otherDataKeys)) {
					otherDataKeys.forEach((key: string) => {
						returnData.otherDatas[key] = res.data[key];
					});
				}
			}
			return returnData;
		};
	}
}

const httpServe: CustomAxiosHttp = new CustomAxiosHttp({ reqCallback, resCallback, resErrorCallback });

export default httpServe;
